package com.frxuexi.park2301

import android.Manifest
import android.R
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat.stopForeground
import androidx.core.content.ContextCompat.getSystemService
import androidx.media3.exoplayer.offline.DownloadService.startForeground
import com.frxuexi.lib_base.db.LatDao
import com.frxuexi.lib_base.entity.LatBean
import dagger.hilt.android.AndroidEntryPoint
import java.util.Locale
import javax.inject.Inject


@AndroidEntryPoint
class LocationTrackingService : Service() {
    private var locationManager: LocationManager? = null
    private var handler: Handler? = null
    private var locationRunnable: Runnable? = null

    @Inject
    lateinit var latDao: LatDao

    @RequiresApi(Build.VERSION_CODES.O)
    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager?
        handler = Handler()

        // 创建通知渠道（Android 8.0+需要）
        createNotificationChannel()

        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification("正在启动位置跟踪..."))
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "位置跟踪",
                NotificationManager.IMPORTANCE_LOW
            )
            val manager: NotificationManager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotification(content: String): Notification {
        return Notification.Builder(this, CHANNEL_ID)
            .setContentTitle("位置跟踪服务")
            .setContentText(content)
            .setSmallIcon(com.frxuexi.park2301.R.drawable.car)
            .build()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startLocationUpdates()
        return START_STICKY
    }

    private fun startLocationUpdates() {
        locationRunnable = object : Runnable {
            override fun run() {
                requestLocationUpdate()
                handler?.postDelayed(this, INTERVAL)
            }
        }
        handler?.post(locationRunnable as Runnable)
    }

    private fun requestLocationUpdate() {
        if (ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_FINE_LOCATION")
            != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        locationManager!!.requestSingleUpdate(
            LocationManager.GPS_PROVIDER,
            object : LocationListener {
                @RequiresApi(Build.VERSION_CODES.O)
                override fun onLocationChanged(location: Location) {
                    val latitude: Double = location.getLatitude()
                    val longitude: Double = location.getLongitude()
                    val insertLoc = latDao.insertLoc(LatBean(null, latitude, longitude))
                    Log.i("===",insertLoc.toString())
                    // 更新通知
                    updateNotification(latitude, longitude)

                    // 也可以在这里保存到数据库或发送到服务器
                }

                override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
                override fun onProviderEnabled(provider: String) {}
                override fun onProviderDisabled(provider: String) {}
            },
            null
        )
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun updateNotification(latitude: Double, longitude: Double) {
        val content = String.format(
            Locale.getDefault(),
            "当前位置: %.6f, %.6f", latitude, longitude
        )
        val notification = createNotification(content)
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification)
    }

    override fun onDestroy() {
        super.onDestroy()
        locationRunnable?.let { handler?.removeCallbacks(it) }
        stopForeground(true)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    companion object {
        private const val NOTIFICATION_ID = 123
        private const val CHANNEL_ID = "location_tracking_channel"
        private const val INTERVAL = (30 * 1000 // 30秒
                ).toLong()
    }
}